#include "leddevicenode.h"
#include "ui_leddevicenode.h"

LedDeviceNode::LedDeviceNode(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LedDeviceNode)
{
    ui->setupUi(this);
    //初始化
    mserver = new QTcpServer();

    connect(mserver,&QTcpServer::newConnection,this,&LedDeviceNode::new_client);


    //启动
    mserver->listen(QHostAddress::Any,5678);
}

LedDeviceNode::~LedDeviceNode()
{
    delete ui;
}

void LedDeviceNode::new_client()
{
    QTcpSocket *msocket = mserver->nextPendingConnection();
    connect(msocket,&QTcpSocket::readyRead,this,&LedDeviceNode::read_data);
}

void LedDeviceNode::read_data()
{
    QTcpSocket *msocket = qobject_cast<QTcpSocket*>(sender());

    QString data = msocket->readAll();

    //数据解析{led1:open,led2:close}
    if(data.startsWith("{")&&data.endsWith("}"))
    {
        data.remove("{").remove("}");
        QStringList list = data.split(",");
        if(list.size()<2) return;
        QString tmp = list.at(0);
        tmp.remove("led1:");
        if(tmp=="open")
        {
            ui->led1->setStyleSheet("border-image: url(:/light-on.png);");
        }
        else if(tmp == "close"){
            ui->led1->setStyleSheet("border-image: url(:/light-off.png);");
        }

        tmp = list.at(1);
        tmp.remove("led2:");
        if(tmp=="open")
        {
              ui->led2->setStyleSheet("border-image: url(:/light-on.png);");
        }
        else if(tmp == "close"){
              ui->led2->setStyleSheet("border-image: url(:/light-off.png);");
        }

    }



}
